package com.na.game;

import java.lang.reflect.Constructor;

import android.app.Activity;
import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

import com.na.game.GameManager.Clazz;
import com.na.game.opengl.GLGameMain;
import com.na.game.util.GameConfig;
import com.na.game.util.Util;

public class GameActivity extends Activity implements Clazz {

	private GameEntity game;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			String entityClass = Util.getAppMetaString(this, "game_entity_class");

			Class clazz = Class.forName(entityClass);
			Constructor con = clazz.getConstructor(GameActivity.class);
			game = (GameEntity) con.newInstance(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		boolean useOpenGL = Util.getAppMetaBoolean(this, "useOpenGL");
		GameConfig.useOpenGL = useOpenGL;
		SurfaceView view;
		if (useOpenGL) {
			view = createOpenGLView();
		} else {
			view = createView();
		}
		view.setId(10000);
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.requestFocus();
		setContentView(view);
	}
	
	private SurfaceView createView() {
		SurfaceView view = new SurfaceView(this);
		GameMain gm = new GameMain(this, view);
		view.setOnTouchListener(gm);
		view.setOnKeyListener(gm);
		view.getHolder().addCallback(new SurfaceHolderCallback(gm));
		return view;
	}
	
	private SurfaceView createOpenGLView() {
		GLSurfaceView view = new GLSurfaceView(this);
		GLGameMain gm = new GLGameMain(this, view);
		view.setOnTouchListener(gm);
		view.setOnKeyListener(gm);
		view.setRenderer(gm);
		view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
		return view;
	}
	
	public GameEntity getGameEntity() {
		return game;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		game.invoke(GameEntity.FUNC_ON_ACTIVITY_RESULT, null, requestCode, resultCode, data);
	}
	
	@Override
	public Class<?> getClazz() {
		return getClass();
	}
	
	private class SurfaceHolderCallback implements Callback {

		private GameMain main;
		
		private SurfaceHolderCallback(GameMain main) {
			this.main = main;
		}
		
		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			main.start();
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
		}
		
	}
}
